package test.san.baseproject.net

import android.util.Log
import okhttp3.*
import test.san.baseproject.util.ThreadUtil
import java.io.IOException

// 发送网络请求类
class NetManager private constructor() {
    companion object {
        val manager by lazy { NetManager() }
    }

    val client by lazy { OkHttpClient() }

    // 发送网络请求
    fun <PESPONSE>sendRequest(req: MRequest<PESPONSE>) {
        val request = Request.Builder().url(req.url).get().build()
        client.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                Log.e("HomeFragment", "获取数据失败")
                ThreadUtil.runOnMainThread(object :Runnable{
                    override fun run() {
                        req.handler.onError(e.message)
                    }
                })
            }

            override fun onResponse(call: Call, response: Response) {
                val result = response.body?.string()
                val parseResult = req.parseResult(result)


                // 刷新列表
                ThreadUtil.runOnMainThread(object :Runnable{
                    override fun run() {
                        req.handler.onSuccess(parseResult)
                    }
                })
            }
        })
    }
}